package com.liuwei.spring.cloud.common.utils;/**
 * @author : VelocityHelper
 * @version V1.0
 * @date: 2023/12/17 10:31 PM
 * @Description: TODO
 */

import org.apache.commons.collections4.MapUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

/**
 * @author : VelocityHelper
 * @version V1.0
 * @date: 2023/12/17 10:31 PM
 * @Description: TODO
 */
public class VelocityHelper {

    static {
        Velocity.init();
    }


    /**
     * Velocity 文本模板渲染方法; 默认占位符 ${name}
     * @param tmp
     * @param ctx
     * @return
     */
    public static String render(String tmp, Map<String,Object> ctx){
        VelocityContext context = new VelocityContext();
        MapUtils.emptyIfNull(ctx).entrySet().forEach(x -> {
            context.put(x.getKey(), x.getValue());
        });

        StringWriter writer = new StringWriter();
        Velocity.evaluate(context, writer, "", new StringReader(tmp));
        return writer.toString();
    }
}
